package com.pulanit.pangu.admin.web.controller.business;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pulanit.pangu.admin.business.api.entity.*;
import com.pulanit.pangu.admin.business.api.service.IArticleService;
import com.pulanit.pangu.admin.business.api.service.IColumnEditService;
import com.pulanit.pangu.admin.business.api.service.IColumnService;
import com.pulanit.pangu.admin.business.api.param.ColumnPageIn;
import cn.hutool.core.lang.Assert;
import com.gitee.pulanos.pangu.framework.sdk.dto.Result;
import com.gitee.pulanos.pangu.framework.sdk.dto.page.PageResult;
import com.pulanit.pangu.admin.business.dao.mapper.ColumnEditMapper;
import com.pulanit.pangu.admin.system.api.entity.RoleEntity;
import com.pulanit.pangu.admin.system.api.entity.UserEntity;
import com.pulanit.pangu.admin.system.api.param.PageIn;
import com.pulanit.pangu.admin.system.dao.mapper.RoleMapper;
import com.pulanit.pangu.admin.system.dao.mapper.UserMapper;
import com.pulanit.pangu.admin.system.manager.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import com.gitee.pulanos.pangu.framework.sdk.dto.page.PagingUtil;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 栏目表 前端控制器
 * </p>
 *
 * @author 天鸣
 * @since 2024-03-04
 */
@RestController
@RequestMapping("/api/business/column")
public class ColumnController {

    @Autowired
    private IColumnService columnService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserManager userManager;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IColumnEditService columnEditService;
    /**
     * 分页
     */
    @GetMapping("/page")
    public Result<PageResult<Column>> list(ColumnPageIn columnPageIn)
    {
        Page page = PagingUtil.createPage(columnPageIn);
        LambdaQueryWrapper<Column> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(columnPageIn.getKeyword()), Column::getColumnName, columnPageIn.getKeyword())
                .orderByAsc(Column::getSort).orderByDesc(Column::getCreateTime);
        Page<Column> resultPage = columnService.page(page, wrapper);
        return Result.success(PagingUtil.transformPageResult(resultPage));
    }

    /**
    * 获取列表-字典
    *
    * @return
    */
    @GetMapping("/dicList")
    public Result<List<HashMap>> dicList() {
        LambdaQueryWrapper<Column> wrapper= new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Column::getSort);
       List<Column> list = columnService.list(wrapper);
        List<HashMap> hashMaps = new ArrayList<>();
        list.forEach(item->{
           HashMap<String, Object> hashMap = new HashMap<>();
           hashMap.put("label",item.getColumnName());
           hashMap.put("value",item.getId());
           hashMaps.add(hashMap);
       });
       return Result.success(hashMaps);
    }

    /**
     * 获取详情
     * @return
     */
    @GetMapping("/detail")
    public Result<Column> detail(@RequestParam("id") Long id){
        Assert.notNull(id, "ID 不能为空");
        Column column = columnService.getById(id);
        return Result.success(column);
    }

    /**
     * 保存
     * @param column
     * @return
     */
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Column column){
        column.setCreateTime(DateTime.now().toLocalDateTime());
        columnService.save(column);
        return Result.success();
    }

    /**
     * 修改
     * @param column
     * @return
     */
    @PostMapping("/update")
    public Result<Void> update(@RequestBody Column column){
        columnService.updateById(column);
        return Result.success();
    }

    /**
     * 获取领域列表专家
     *
     * @return
     */
    @GetMapping("/columnEdit")
    public Result<List<UserEntity>> columnEdit(@RequestParam("columnId") Long id) {
        Assert.notNull(id, "ID 不能为空");
        //搜索该领域下用户
        LambdaQueryWrapper<ColumnEdit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ColumnEdit::getColumnId, id);
        List<ColumnEdit> list = columnEditService.list(lambdaQueryWrapper);
        List<Long> userIds = list.stream().map(ColumnEdit::getEditUserId).collect(Collectors.toList());
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(UserEntity.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("password"));
        List<UserEntity> userEntities = ListUtil.list(false);
        if (userIds.size() > 0) {
            userEntities = userMapper.selectBatchIds(userIds);
        }
        return Result.success(userEntities);
    }

    /**
     * 获取非领域列表专家
     *
     * @return
     */
    @GetMapping("/unColumnEdit")
    public Result<PageResult<UserEntity>> unColumnEdit(PageIn pageIn) {
        Page<UserEntity> page = PagingUtil.createPage(pageIn);
        //搜索角色id通过专家标志
        LambdaQueryWrapper<RoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleEntity::getRoleKey, "edit").last("limit 1");
        List<RoleEntity> roleEntities = roleMapper.selectList(wrapper);
        //获取专家用户
        List<UserEntity> userEntities = userManager.listUsersByRoleId(roleEntities.get(0).getId());

        //搜索该领域下用户
        LambdaQueryWrapper<ColumnEdit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ColumnEdit::getColumnId, pageIn.getColumnId());
        List<ColumnEdit> list = columnEditService.list(lambdaQueryWrapper);
        List<Long> userIds = list.stream().map(ColumnEdit::getEditUserId).collect(Collectors.toList());

        //去掉领域下已经存在的用户
        List<UserEntity> collect = userEntities.stream().filter(item -> !ArrayUtil.containsAny(userIds.toArray(), item.getId())).collect(Collectors.toList());

        //手动分页
        List<UserEntity> resultCollect = new ArrayList<>();
        int totalSize;
        int totalPage;
        totalSize = collect.size();
        totalPage = PageUtil.totalPage(totalSize, Convert.toInt(page.getSize()));
        if (page.getCurrent() - 1 <= totalPage) {
            resultCollect = CollUtil.page(Convert.toInt(page.getCurrent() - 1), Convert.toInt(page.getSize()), collect);

        }
        return Result.success(PagingUtil.transformPageResult(page, resultCollect));
    }


    /**
     * 关联领域专家
     *
     * @return
     */
    @PostMapping("/grantColumnEdit")
    public Result<Void> grantColumnEdit(@RequestParam("columnId") Long columnId, @RequestParam("ids") List<Long> ids) {
        Assert.notNull(columnId, "领域 ID 不能为空");
        Assert.notEmpty(ids, "人员 ID 不能为空");
        for (int i = 0; i < ids.size(); i++) {
            ColumnEdit columnEdit = new ColumnEdit();
            columnEdit.setColumnId(columnId);
            columnEdit.setEditUserId(ids.get(i));
            columnEditService.save(columnEdit);
        }
        return Result.success();
    }

    /**
     * 取消关联领域专家
     *
     * @return
     */
    @PostMapping("/cancelColumnEdit")
    public Result<Void> cancelColumnEdit(@RequestParam("columnId") Long columnId, @RequestParam List<Long> ids) {
        Assert.notNull(columnId, "领域 ID 不能为空");
        Assert.notEmpty(ids, "人员 ID 不能为空");
        for (int i = 0; i < ids.size(); i++) {
            LambdaQueryWrapper<ColumnEdit> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ColumnEdit::getColumnId,columnId);
            wrapper.eq(ColumnEdit::getEditUserId,ids.get(i));
            columnEditService.remove(wrapper);
        }
        return Result.success();
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result<Void> delete(@RequestParam("id") Long id){
        Assert.notNull(id, "ID 不能为空");
        LambdaQueryWrapper<ColumnEdit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ColumnEdit::getColumnId, id);
        long count = columnEditService.count(wrapper);
        if (count > 0) {
            return Result.fail("有编辑在该栏目下，不可以删除");
        }

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getFieldId, id);
        long count1 = articleService.count(queryWrapper);
        if (count1 > 0) {
            return Result.fail("有文稿在该栏目下，不可以删除");
        }
        columnService.removeById(id);
        return Result.success();
    }

    /**
     * 批量删除
     *
     */
     @PostMapping("/batchDelete")
     public Result<Void> batchDelete(@RequestParam List<Long> ids) {
        Assert.notEmpty(ids, "ID 不能为空");
        columnService.removeBatchByIds(ids);
        return Result.success();
     }

}
